/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brucexx.wedding.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.brucexx.wedding.dao.BaseModelDAO;
import com.brucexx.wedding.dao.PermissionDAO;
import com.brucexx.wedding.model.Comment;
import com.brucexx.wedding.model.FaceMapping;
import com.brucexx.wedding.model.Story;
import com.brucexx.wedding.util.BeanHelper;
import com.brucexx.wedding.util.DateHelper;
import com.brucexx.wedding.util.NumberHelper;
import com.brucexx.wedding.util.StringHelper;
import com.google.appengine.api.datastore.Text;

/**
 * 
 * @author BruceXX email:brucest0078@gmail.com
 * 
 */
@Controller
public class CommentController {

	private static final Log logger = LogFactory
			.getLog(CommentController.class);
	public static final String[] randomName = { "匿名" };

	@RequestMapping(value = "/commend_last.action", method = RequestMethod.GET)
	public void loadLastComment(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		String topic = StringHelper.null2String(request.getParameter("topic"));
		if (StringHelper.isEmpty(topic)) {
			topic = "04";
		}
		String gql = "select   from " + Comment.class.getName()
				+ " where topic=='" + topic + "' order by gmtCreate desc range 0,5";
		JSONArray jsonList = new JSONArray();

		List<Comment> list = BaseModelDAO.executeSqlForList(gql);
		for (Comment comment : list) {
			JSONObject tmp = new JSONObject();
			BeanHelper.copyProperties2JSON(tmp, comment, "commentContent",
					"gmtCreate");
			tmp.put("commentContent", comment.getCommentContent().getValue());
			tmp.put("gmtCreate", DateHelper.getChinaDateTime(comment.getGmtCreate()));
			jsonList.add(tmp);
		}
		response.getWriter().write(jsonList.toString());
	}

	@RequestMapping(value = "/commend.action", method = RequestMethod.GET)
	public String loadPage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		String action = StringHelper
				.null2String(request.getParameter("action"));
		String id = StringHelper.null2String(request.getParameter("id"));
		String flag = StringHelper.null2String(request.getParameter("flag"));

		if (action.equalsIgnoreCase("load")) {
			int page = NumberHelper.string2Int(request.getParameter("page"), 1) - 1;
			int pageCount = NumberHelper.string2Int(
					request.getParameter("pageCount"), 20);
			int curNum = page * pageCount;
			JSONArray jsonList = new JSONArray();
			String sizeGql="select  from " + Comment.class.getName()
			+ "  where oid=='" + id + "' && topic=='" + flag
			+ "'";
			int totalSize = BaseModelDAO.getCountBySql(sizeGql);
			logger.info("query story gql["+sizeGql+"]totalsize=>"+totalSize);
			int curOffset=0;
			if (totalSize >= (curNum + pageCount)) {
				curOffset =  curNum + pageCount;
			}else{
				curOffset= totalSize;
			}
			//
			String gql = "select  from " + Comment.class.getName()
					+ "  where oid=='" + id + "' && topic=='" + flag
					+ "'  order by gmtCreate desc";

			List<Comment> list =BaseModelDAO.executeSqlForPage(gql, curNum, curOffset);
			JSONObject obj = new JSONObject();
			obj.put("totalCount", totalSize);
			obj.put("pageCount", pageCount);
			jsonList.add(obj);
			for (Comment comment:list ) {
				JSONObject tmp = new JSONObject();

				BeanHelper.copyProperties2JSON(tmp, comment, "commentContent",
						"gmtCreate");
				tmp.put("commentContent", FaceMapping.getReplaceText(comment
						.getCommentContent().getValue()));
				tmp.put("gmtCreate",
						DateHelper.getChinaDateTime(comment.getGmtCreate()));

				jsonList.add(tmp);
			}

			logger.info("load page str[" + jsonList + "]");
			response.getWriter().write(jsonList.toString());
			return null;
		} else if (action.equalsIgnoreCase("add")) {
			String name = StringHelper
					.null2String(request.getParameter("name"));
			if (StringHelper.isEmpty(name)) {
				// name = randomName[new Random().nextInt(randomName.length -
				// 1)];
				name = randomName[0];
			}
			String commend = StringHelper.null2String(request
					.getParameter("commend"));
			Comment comment = new Comment();
			comment.setUserName(name);
			comment.setCommentContent(new Text(commend));
			comment.setGmtCreate(new Date());
			comment.setTopic(flag);
			comment.setOid(id);
			BaseModelDAO.addOrUpdate(comment);

			Story story = BaseModelDAO.loadById(
					NumberHelper.string2Long(id, -1), Story.class);
			story.setCommentAmount(story.getCommentAmount() + 1);
			BaseModelDAO.addOrUpdate(story);
			response.getWriter().write("1");
			return null;
		} else if (action.equalsIgnoreCase("del")) {
			if (!PermissionDAO.isAdmin(request.getSession())) {
				return "admin/no_permission";
			}
		}
		return null;
	}
}
